import { ref, reactive, shallowRef } from 'vue'
import * as echarts from 'echarts'
import getInitOption from '../options/TemperatureOption'

const chartInstance = shallowRef() // 图表实例
const allTemperatureData = reactive([]) // 数据
const maxScale = ref(30) // 最大显示点数
const config = ref({ max: 24, min: 20 }) // 图表配置
const titleFontSize = ref(0) // 图表字体大小
const temperatureRef = shallowRef()

function registerTemperature(temperature) {
  temperatureRef.value = temperature
}
function initChart() {
  chartInstance.value = echarts.init(temperatureRef.value, 'dark')
  chartInstance.value.setOption(getInitOption(config.value))
}
function screenAdapter() {
  titleFontSize.value = (temperatureRef.value.offsetWidth / 100) * 2.5
  const apdaterOption = {
    xAxis: {
      nameTextStyle: {
        fontSize: titleFontSize.value
      }
    },
    yAxis: {
      nameTextStyle: {
        fontSize: titleFontSize.value
      }
    }
  }
  chartInstance.value.setOption(apdaterOption)
  chartInstance.value.resize()
}
function updateTemperature(time, data, status) {
  const temperatureData = {
    name: time,
    value: [time, data],
    symbolSize: status === 1 ? 10 : 20,
    symbol: status === 1 ? 'circle' : 'triangle',
    itemStyle:
      status === 1
        ? {
            borderWidth: 3,
            borderColor: '#86efac',
            color: '#6AB887'
          }
        : {
            borderWidth: 3,
            borderColor: '#EE6666',
            color: 'yellow'
          }
  }
  allTemperatureData.push(temperatureData)
  while (allTemperatureData.length > maxScale.value) {
    allTemperatureData.shift()
  }
  updateTemperatureChart()
}
function updateTemperatureChart() {
  const dataOption = {
    series: [
      {
        data: allTemperatureData
      }
    ]
  }
  chartInstance.value.setOption(dataOption)
}
function clearAllTemperatureData() {
  allTemperatureData.splice(0, allTemperatureData.length)
  updateTemperatureChart()
}

export const useTemperature = () => {
  return {
    registerTemperature,
    initChart,
    screenAdapter,
    updateTemperature,
    clearAllTemperatureData
  }
}
